package controller

import (
	"kingbloc.dts/models"
	"kingbloc.dts/services"
	"kingbloc.dts/tools"
	"kingbloc.util/util"
	"net/http"
	"strconv"
	"strings"
)

type MyFriend struct {
	Price     float64     `json:"price"`
	AccountId int64       `json:"aid"`
	SsoId     int64       `json:"uid"`
	OrderId   int64       `json:"oid"`
	Name      string      `json:"name"` // 就是手机号
	Children  interface{} `json:"children"`
}

func MyFriends(rep http.ResponseWriter, req *http.Request) {

	loginUser := validateUserInfo(req)

	if loginUser == nil {
		rep.WriteHeader(403)
		return
	}
	if strings.ToLower(req.Method) != "get" {
		rep.WriteHeader(403)
		return
	}
	//

	targetOrderId := req.URL.Query().Get("oid")

	if targetOrderId == "" { // 目标用户id不存在就获取自己下面两个单子
		rep.WriteHeader(200)
		return
	}

	oid, _ := strconv.ParseInt(targetOrderId, 10, 64)
	targetOrder := new(model.Orderr).ById(oid)

	targetAccount := new(model.Account).ById(targetOrder.AccountId)
	//

	if targetAccount == nil || targetAccount.Id == 0 {
		util.WriteJSON(rep, []string{})
		return
	}

	myOrders := service.FindOrdersByParentLayerOrderId(targetOrder.Id)
	if len(myOrders) == 0 {
		util.WriteJSON(rep, []string{})
		return

	}

	nextFriends := make([]*MyFriend, len(myOrders))
	for k, v := range myOrders {
		nextFriends[k] = new(MyFriend).OrderTransfromToMyFriend(v)
	}

	util.WriteJSON(rep, nextFriends)

}

// 我的直接推荐的单子
func MyDirectiveOrders(rep http.ResponseWriter, req *http.Request) {
	user := validateUserInfo(req)

	if user == nil {
		rep.WriteHeader(403)
		return
	}

	myAccount := service.FindAccountBySSOId(user.Id)

	if myAccount == nil || myAccount.Id == 0 {
		rep.WriteHeader(403)
		return
	}

	orders := service.MyRecommended(myAccount.Id)
	if len(orders) == 0 {
		rep.WriteHeader(200)
		return
	}

	orderIds := make([]int64, len(orders))
	for k, v := range orders {
		orderIds[k] = v.Id
	}

	util.WriteJSON(rep, orderIds)

}

func (mf *MyFriend) OrderTransfromToMyFriend(order *model.Orderr) *MyFriend {
	account := new(model.Account).ById(order.AccountId)
	user1 := tool.UserInfoById(account.SsoUserId)
	//
	mf.AccountId = order.AccountId
	mf.Name = user1.Mobile
	mf.OrderId = order.Id
	mf.SsoId = user1.Id
	mf.Price = order.Price
	mf.Children = []string{}
	return mf
}
